package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.assistant.common.enums.ExcelTypeEnum;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.engine.protect.core.annotation.NoSignCrypto;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.dict.DictQueryVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.*;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.system.common.enums.CardTypeEnum;
import com.bifang.module.system.core.dao.model.ExcelModel;
import com.bifang.module.system.core.dao.model.ExcelParam;
import com.bifang.module.system.core.dao.service.ExcelModelService;
import com.bifang.module.system.core.dao.service.ExcelParamService;
import com.bifang.module.system.core.dao.service.SysDictService;
import com.bifang.module.system.core.integration.impl.ExcelIntegrationImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.eduCompany.EduCompanyVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduStudentStatus.*;
import com.jwsoft.manager.core.dao.model.EduSchool;
import com.jwsoft.manager.core.dao.model.EduStudentStatus;
import com.jwsoft.manager.core.dao.model.EduhCompany;
import com.jwsoft.manager.core.dao.model.EduhStudentStatus;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduStudentStatusIntegration;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生学籍表业务实现类
 *
 * @author wangtao
 * @since 2022-12-28
 */
@ApiService(funcCode = "EduStudentStatus", title = "学生学籍表")
public class EduStudentStatusIntegrationImpl implements EduStudentStatusIntegration {

    @Autowired
    public EduStudentStatusService eduStudentStatusService;

    @Autowired
    private EduSchoolService eduSchoolService;

    @Autowired
    private ExcelIntegrationImpl excelIntegration;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private ExcelModelService excelModelService;

    @Autowired
    private ExcelParamService excelParamService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private ExcelCommonHelper excelCommonHelper;

    @Autowired
    private DictIntegration dictIntegration;
    @Autowired
    private EduDataTaskDetailService eduDataTaskDetailService;

    @Autowired
    public EduhStudentStatusService eduhStudentStatusService;
    public static final String handleTable = "edu_student_status";

    @Override
    @OpApi(funcCode = "EduStudentStatus0001", title = "学生学籍表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentStatusVO> getList(EduStudentStatusQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        //取出脱敏字段，判断是否为空
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null){
            desensitizeFlag = true;
        }
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),handleTable);
        if (!queryHistoryFlag) {
            QueryWrapper<EduStudentStatus> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getYear()),
                            EduStudentStatus::getYear,
                            vo.getYear())
                    .eq(!ObjectUtils.isEmpty(vo.getFullName()),
                            EduStudentStatus::getFullName,
                            vo.getFullName())
                    .eq(!ObjectUtils.isEmpty(vo.getIdcard()),
                            EduStudentStatus::getIdcard,
                            vo.getIdcard())
                    .eq(!ObjectUtils.isEmpty(vo.getFatherName()),
                            EduStudentStatus::getFatherName,
                            vo.getFatherName())
                    .eq(!ObjectUtils.isEmpty(vo.getFatherCardType()),
                            EduStudentStatus::getFatherCardType,
                            vo.getFatherCardType())
                    .eq(!ObjectUtils.isEmpty(vo.getFatherIdcard()),
                            EduStudentStatus::getFatherIdcard,
                            vo.getFatherIdcard())
                    .eq(!ObjectUtils.isEmpty(vo.getMotherName()),
                            EduStudentStatus::getMotherName,
                            vo.getMotherName())
                    .eq(!ObjectUtils.isEmpty(vo.getMotherCardType()),
                            EduStudentStatus::getMotherCardType,
                            vo.getMotherCardType())
                    .eq(!ObjectUtils.isEmpty(vo.getMotherIdcard()),
                            EduStudentStatus::getMotherIdcard,
                            vo.getMotherIdcard())
                    .eq(!ObjectUtils.isEmpty(vo.getSchoolId()),
                            EduStudentStatus::getSchoolId,
                            vo.getSchoolId());
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduStudentStatus> list = eduStudentStatusService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduStudentStatus> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduStudentStatusVO> resultList = Convert.toList(EduStudentStatusVO.class, pageInfo.getList());
            // 转义数据字典值
            // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
            if (desensitizeFlag) {
                for (EduStudentStatusVO eduStudentStatusVO : resultList) {
                    eduStudentStatusVO.setFullName(EduDesensitizeUtil.desensitizeFullName(eduStudentStatusVO.getFullName()));
                    eduStudentStatusVO.setFatherName(EduDesensitizeUtil.desensitizeFullName(eduStudentStatusVO.getFatherName()));
                    eduStudentStatusVO.setMotherName(EduDesensitizeUtil.desensitizeFullName(eduStudentStatusVO.getMotherName()));
                    eduStudentStatusVO.setIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentStatusVO.getIdcard()));
                    eduStudentStatusVO.setMotherIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentStatusVO.getMotherIdcard()));
                    eduStudentStatusVO.setFatherIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentStatusVO.getFatherIdcard()));
                }
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }else {
            // 迁移过后，判断是否加密
            Boolean encryptFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), handleTable));
            //如果加密，把查询条件加密
            if (encryptFlag) {
                if (StringUtils.isNotBlank(vo.getIdcard())){
                    vo.setIdcard(CommonSecureUtil.sm4Encrypt(vo.getIdcard()));
                }
                if (StringUtils.isNotBlank(vo.getFullName())){
                    vo.setFullName(CommonSecureUtil.sm4Encrypt(vo.getFullName()));
                }
                if (StringUtils.isNotBlank(vo.getFatherIdcard())){
                    vo.setFatherIdcard(CommonSecureUtil.sm4Encrypt(vo.getFatherIdcard()));
                }
                if (StringUtils.isNotBlank(vo.getFatherName())){
                    vo.setFatherName(CommonSecureUtil.sm4Encrypt(vo.getFatherName()));
                }
                if (StringUtils.isNotBlank(vo.getMotherName())){
                    vo.setMotherName(CommonSecureUtil.sm4Encrypt(vo.getMotherName()));
                }
                if (StringUtils.isNotBlank(vo.getMotherIdcard())){
                    vo.setMotherIdcard(CommonSecureUtil.sm4Encrypt(vo.getMotherIdcard()));
                }
            }
            QueryWrapper<EduhStudentStatus> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(!ObjectUtils.isEmpty(vo.getYear()),
                            EduhStudentStatus::getYear,
                            vo.getYear())
                    .eq(!ObjectUtils.isEmpty(vo.getFullName()),
                            EduhStudentStatus::getFullName,
                            vo.getFullName())
                    .eq(!ObjectUtils.isEmpty(vo.getIdcard()),
                            EduhStudentStatus::getIdcard,
                            vo.getIdcard())
                    .eq(!ObjectUtils.isEmpty(vo.getFatherName()),
                            EduhStudentStatus::getFatherName,
                            vo.getFatherName())
                    .eq(!ObjectUtils.isEmpty(vo.getFatherCardType()),
                            EduhStudentStatus::getFatherCardType,
                            vo.getFatherCardType())
                    .eq(!ObjectUtils.isEmpty(vo.getFatherIdcard()),
                            EduhStudentStatus::getFatherIdcard,
                            vo.getFatherIdcard())
                    .eq(!ObjectUtils.isEmpty(vo.getMotherName()),
                            EduhStudentStatus::getMotherName,
                            vo.getMotherName())
                    .eq(!ObjectUtils.isEmpty(vo.getMotherCardType()),
                            EduhStudentStatus::getMotherCardType,
                            vo.getMotherCardType())
                    .eq(!ObjectUtils.isEmpty(vo.getMotherIdcard()),
                            EduhStudentStatus::getMotherIdcard,
                            vo.getMotherIdcard())
                    .eq(!ObjectUtils.isEmpty(vo.getSchoolId()),
                            EduhStudentStatus::getSchoolId,
                            vo.getSchoolId());
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduhStudentStatus> list = eduhStudentStatusService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            PageInfo<EduhStudentStatus> pageInfo = new PageInfo<>(list);
            // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
            List<EduStudentStatusVO> resultList = Convert.toList(EduStudentStatusVO.class, pageInfo.getList());

            for (EduStudentStatusVO eduStudentStatusVO : resultList) {
                if ("1".equals(eduStudentStatusVO.getEncryptFlag())) {
                    if (StringUtils.isNotBlank(eduStudentStatusVO.getIdcard())) {
                        eduStudentStatusVO.setIdcard(CommonSecureUtil.sm4Decrypt(eduStudentStatusVO.getIdcard()));
                    }
                    if (StringUtils.isNotBlank(eduStudentStatusVO.getFullName())) {
                        eduStudentStatusVO.setFullName(CommonSecureUtil.sm4Decrypt(eduStudentStatusVO.getFullName()));
                    }
                    if (StringUtils.isNotBlank(eduStudentStatusVO.getFatherIdcard())) {
                        eduStudentStatusVO.setFatherIdcard(CommonSecureUtil.sm4Decrypt(eduStudentStatusVO.getFatherIdcard()));
                    }
                    if (StringUtils.isNotBlank(eduStudentStatusVO.getFatherName())) {
                        eduStudentStatusVO.setFatherName(CommonSecureUtil.sm4Decrypt(eduStudentStatusVO.getFatherName()));
                    }
                    if (StringUtils.isNotBlank(eduStudentStatusVO.getMotherName())) {
                        eduStudentStatusVO.setMotherName(CommonSecureUtil.sm4Decrypt(eduStudentStatusVO.getMotherName()));
                    }
                    if (StringUtils.isNotBlank(eduStudentStatusVO.getMotherIdcard())) {
                        eduStudentStatusVO.setMotherIdcard(CommonSecureUtil.sm4Decrypt(eduStudentStatusVO.getMotherIdcard()));
                    }
                }
            }
            // 转义数据字典值
            // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
            if (desensitizeFlag) {
                for (EduStudentStatusVO eduStudentStatusVO : resultList) {
                    eduStudentStatusVO.setFullName(EduDesensitizeUtil.desensitizeFullName(eduStudentStatusVO.getFullName()));
                    eduStudentStatusVO.setFatherName(EduDesensitizeUtil.desensitizeFullName(eduStudentStatusVO.getFatherName()));
                    eduStudentStatusVO.setMotherName(EduDesensitizeUtil.desensitizeFullName(eduStudentStatusVO.getMotherName()));
                    eduStudentStatusVO.setIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentStatusVO.getIdcard()));
                    eduStudentStatusVO.setMotherIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentStatusVO.getMotherIdcard()));
                    eduStudentStatusVO.setFatherIdcard(EduDesensitizeUtil.desensitizeIdcard(eduStudentStatusVO.getFatherIdcard()));
                }
            }
            return PagerUtil.parsePagerVo(resultList, pageInfo);
        }
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0002", title = "学生学籍表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduStudentStatusVO getById(EduStudentStatusKeyVO vo) {
        //判断是否迁移过
        EduStudentStatusVO result;
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), handleTable));
        if (!queryHistoryFlag) {
            // 没有迁移查询
            EduStudentStatus entity = eduStudentStatusService.getById(vo.getStudentStatusId());
            if (ObjectUtils.isEmpty(entity)) {
                throw new AppException("查询不到详细信息!");
            }
             result = Convert.convert(EduStudentStatusVO.class, entity);
        }else {
             EduhStudentStatus eduHospitalStatus =  eduhStudentStatusService.getById(vo.getStudentStatusId());

            if (ObjectUtils.isEmpty(eduHospitalStatus)) {
                throw new AppException("查询不到详细信息!");
            }
            //解密
            if ("1".equals(eduHospitalStatus.getEncryptFlag())) {
                if (StringUtils.isNotBlank(eduHospitalStatus.getIdcard())) {
                    eduHospitalStatus.setIdcard(CommonSecureUtil.sm4Decrypt(eduHospitalStatus.getIdcard()));
                }
                if (StringUtils.isNotBlank(eduHospitalStatus.getFullName())) {
                    eduHospitalStatus.setFullName(CommonSecureUtil.sm4Decrypt(eduHospitalStatus.getFullName()));
                }
                if (StringUtils.isNotBlank(eduHospitalStatus.getFatherIdcard())) {
                    eduHospitalStatus.setFatherIdcard(CommonSecureUtil.sm4Decrypt(eduHospitalStatus.getFatherIdcard()));
                }
                if (StringUtils.isNotBlank(eduHospitalStatus.getFatherName())) {
                    eduHospitalStatus.setFatherName(CommonSecureUtil.sm4Decrypt(eduHospitalStatus.getFatherName()));
                }
                if (StringUtils.isNotBlank(eduHospitalStatus.getMotherName())) {
                    eduHospitalStatus.setMotherName(CommonSecureUtil.sm4Decrypt(eduHospitalStatus.getMotherName()));
                }
                if (StringUtils.isNotBlank(eduHospitalStatus.getMotherIdcard())) {
                    eduHospitalStatus.setMotherIdcard(CommonSecureUtil.sm4Decrypt(eduHospitalStatus.getMotherIdcard()));
                }
            }
            result = Convert.convert(EduStudentStatusVO.class, eduHospitalStatus);
        }
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "EduStudentStatus0003", title = "学生学籍表保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduStudentStatusVO vo) {
        if (!ObjectUtils.isEmpty(vo.getIdcard())) {
            if (!IdcardUtil.isValidCard(vo.getIdcard())) {
                throw new AppException("学生身份证错误!");
            }
        }
        if (!ObjectUtils.isEmpty(vo.getFatherIdcard()) && !ObjectUtils.isEmpty(vo.getFatherCardType())) {
            if (CardTypeEnum.idcard.getType().equals(vo.getFatherCardType()) && !IdcardUtil.isValidCard(vo.getFatherIdcard())) {
                throw new AppException("父亲身份证有误！");
            }
        }
        if (!ObjectUtils.isEmpty(vo.getMotherIdcard()) && !ObjectUtils.isEmpty(vo.getMotherCardType())) {
            if (CardTypeEnum.idcard.getType().equals(vo.getMotherCardType()) && !IdcardUtil.isValidCard(vo.getMotherIdcard())) {
                throw new AppException("母亲身份证有误！");
            }
        }
        if (!ObjectUtils.isEmpty(vo.getMotherIdcard()) && !ObjectUtils.isEmpty(vo.getFatherIdcard())) {
            if (vo.getFatherIdcard().equalsIgnoreCase(vo.getMotherIdcard())) {
                throw new AppException("父母亲身份证不能重复！");
            }
        }

        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0004", title = "学生学籍表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "EduStudentStatus0004",
            operationName = "学生学籍表新增",
            dataType = "studentStatusId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduStudentStatusVO add(EduStudentStatusVO vo) {
        String schoolId = vo.getSchoolId();
        String idcard = vo.getIdcard();
        if (!ObjectUtils.isEmpty(schoolId)) {
            EduSchool eduSchool = eduSchoolService.getById(schoolId);
            vo.setSchoolName(eduSchool.getSchoolName());
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduStudentStatus entity = Convert.convert(EduStudentStatus.class, vo);
        if (!ObjectUtils.isEmpty(idcard)) {
            QueryWrapper<EduStudentStatus> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduStudentStatus::getIdcard, idcard);
            List<EduStudentStatus> list = eduStudentStatusService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                for (EduStudentStatus eduStudentStatus : list) {
                    entity.setStudentStatusId(eduStudentStatus.getStudentStatusId());
                }
                eduStudentStatusService.updateById(entity);
            } else {
                eduStudentStatusService.save(entity);
            }
        }
        //将主键设置回vo使操作日志可以取到
        vo.setStudentStatusId(entity.getStudentStatusId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0005", title = "学生学籍表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "EduStudentStatus0005",
            operationName = "学生学籍表修改",
            dataType = "studentStatusId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduStudentStatusVO edit(EduStudentStatusVO vo) {
        Boolean queryHistoryFlag = Boolean.TRUE.equals(eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), handleTable));
        if (queryHistoryFlag) {
            throw new AppException("历史数据无法修改");
        }
        String schoolId = vo.getSchoolId();
        if (ObjectUtils.isEmpty(vo.getStudentStatusId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduStudentStatus oldEntity = eduStudentStatusService.getById(vo.getStudentStatusId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduStudentStatus entity = Convert.convert(EduStudentStatus.class, vo);
        if (!ObjectUtils.isEmpty(schoolId)) {
            EduSchool eduSchool = eduSchoolService.getById(schoolId);
            entity.setSchoolName(eduSchool.getSchoolName());
        }
        eduStudentStatusService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0006", title = "学生学籍表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "EduStudentStatus0006",
            operationName = "学生学籍表删除",
            dataType = "studentStatusId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduStudentStatusKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getStudentStatusId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduStudentStatus entity = eduStudentStatusService.getById(vo.getStudentStatusId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduStudentStatusService.removeById(vo.getStudentStatusId());
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0007", title = "学籍信息模板下载", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void downloadModel(ExcelVO vo, HttpServletResponse response) {
        Map<String,List<SelectVO>> dictMap =new HashMap<>();
        dictMap.put("schoolName",getSchoolDictMap());
        vo.setDictMap(dictMap);
        excelIntegration.downloadModel(vo, response);
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0008", title = "学籍信息文件上传", funcType = FuncTypeEnum.insert)
    @NoSignCrypto
    public ExcelReadVO readExcel(ExcelVO vo, MultipartFile file) {
        String areaCode = SessionUtil.getAreaCode();
        ExcelReadVO excelReadVO = new ExcelReadVO();
        excelReadVO.setCount(0);
        ExcelModelVO excelModelVO = this.getModel(vo);
        InputStream in = null;
        try {
            in = file.getInputStream();
            List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);
            List<Map<String, Object>> successList = new ArrayList<>();
            List<Map<String, Object>> errorList = new ArrayList<>();
            List<String> idcardList = new ArrayList<>();

            // 查找所有 学段为小学和初中的 及 统筹区与操作人的统筹区一致的 学校
            QueryWrapper<EduSchool> schoolQueryWrapper = new QueryWrapper<>();
            schoolQueryWrapper.lambda()
                    .in(EduSchool::getSchoolCategory, SchoolCategoryEnum.PRIMARY.getType(), SchoolCategoryEnum.JUNIOR.getType())
                    .eq(!ObjectUtils.isEmpty(areaCode),
                            EduSchool::getAreaCode,
                            areaCode);
            List<EduSchool> schoolList = eduSchoolService.list(schoolQueryWrapper);

            // 学校名称/简称 为键  学校id为值的 map
            Map<String, String> schoolNameMap = schoolList.stream()
                    .collect(Collectors.toMap(EduSchool::getSchoolName, a -> a.getOrgId(), (k1, k2) -> k1));
            Map<String, String> shortNameMap = schoolList.stream()
                    .collect(Collectors.toMap(EduSchool::getShortName, a -> a.getOrgId(), (k1, k2) -> k1));

            for (Map<String, Object> map : list) {
                String fullBack = "";
                boolean flag = false;
                EduStudentStatusVO studentStatusVO = JSON.parseObject(JSON.toJSONString(map), EduStudentStatusVO.class);
                studentStatusVO.setIdcard(studentStatusVO.getIdcard().trim().toUpperCase());
                if (!IdcardUtil.isValidCard(studentStatusVO.getIdcard())) {
                    fullBack += "学生身份证有误！";
                    flag = true;
                }
                if (idcardList.contains(studentStatusVO.getIdcard())) {
                    fullBack += "存在重复学生身份证！";
                    flag = true;
                } else {
                    idcardList.add(studentStatusVO.getIdcard());
                }
                if (ObjectUtils.isEmpty(studentStatusVO.getFullName())) {
                    fullBack += "学生姓名不能为空！";
                    flag = true;
                } else {
                    studentStatusVO.setFullName(
                            Validator.isChinese(studentStatusVO.getFullName())
                                    ? studentStatusVO.getFullName().replaceAll(" ", "").replaceAll(" ", "").trim()
                                    : studentStatusVO.getFullName().trim());
                }

                if (!ObjectUtils.isEmpty(studentStatusVO.getFatherIdcard()) && StringUtils.isNotBlank(studentStatusVO.getFatherIdcard().trim())) {
                    if (StringUtils.isBlank(studentStatusVO.getFatherCardType())) {
                        studentStatusVO.setFatherCardType(CardTypeEnum.idcard.getType());
                    } else if (StringUtils.isBlank(studentStatusVO.getFatherCardType().trim())) {
                        studentStatusVO.setFatherCardType(CardTypeEnum.idcard.getType());
                    } else {
                        //导入是中文情况下处理成数据字典
                        if (StringUtils.isNotBlank(studentStatusVO.getFatherCardType().trim()) && Validator.isChinese(studentStatusVO.getFatherCardType().trim())) {
                            DictQueryVO dictQueryVO = new DictQueryVO();
                            dictQueryVO.setDictField("cardType");
                            dictQueryVO.setDictValue(studentStatusVO.getFatherCardType().trim());
                            String key = dictIntegration.getValue(dictQueryVO);
                            if (StringUtils.isBlank(key)) {
                                fullBack += "父亲证件类型数据格式不对！";
                                flag = true;
                            }
                            studentStatusVO.setFatherCardType(key);
                        }
                    }
                    studentStatusVO.setFatherIdcard(studentStatusVO.getFatherIdcard().trim().toUpperCase());
                    if (CardTypeEnum.idcard.getType().equals(studentStatusVO.getFatherCardType()) && !IdcardUtil.isValidCard(studentStatusVO.getFatherIdcard())) {
                        fullBack += "父亲身份证有误！";
                        flag = true;
                    }
                    studentStatusVO.setFatherName(
                            Validator.isChinese(studentStatusVO.getFatherName())
                                    ? studentStatusVO.getFatherName().replaceAll(" ", "").replaceAll(" ", "").trim()
                                    : studentStatusVO.getFatherName().trim());
                }

                if (!ObjectUtils.isEmpty(studentStatusVO.getMotherIdcard()) && StringUtils.isNotBlank(studentStatusVO.getMotherIdcard().trim())) {
                    if (StringUtils.isBlank(studentStatusVO.getMotherCardType())) {
                        studentStatusVO.setMotherCardType(CardTypeEnum.idcard.getType());
                    } else if (StringUtils.isBlank(studentStatusVO.getMotherCardType().trim())) {
                        studentStatusVO.setMotherCardType(CardTypeEnum.idcard.getType());
                    } else {
                        //导入是中文情况下处理成数据字典
                        if (Validator.isChinese(studentStatusVO.getMotherCardType().trim())) {
                            DictQueryVO dictQueryVO = new DictQueryVO();
                            dictQueryVO.setDictField("cardType");
                            dictQueryVO.setDictValue(studentStatusVO.getMotherCardType().trim());
                            String key = dictIntegration.getValue(dictQueryVO);
                            if (StringUtils.isBlank(key)) {
                                fullBack += "母亲证件类型数据格式不对！";
                                flag = true;
                            }
                            studentStatusVO.setMotherCardType(key);
                        }
                    }
                    studentStatusVO.setMotherIdcard(studentStatusVO.getMotherIdcard().trim().toUpperCase());
                    if (CardTypeEnum.idcard.getType().equals(studentStatusVO.getMotherCardType()) && !IdcardUtil.isValidCard(studentStatusVO.getMotherIdcard())) {
                        fullBack += "母亲身份证有误！";
                        flag = true;
                    }
                    studentStatusVO.setMotherName(
                            Validator.isChinese(studentStatusVO.getMotherName())
                                    ? studentStatusVO.getMotherName().replaceAll(" ", "").replaceAll(" ", "").trim()
                                    : studentStatusVO.getMotherName().trim());
                }

                if(StringUtils.isNotBlank(studentStatusVO.getFatherIdcard())&&StringUtils.isNotBlank(studentStatusVO.getMotherIdcard())){
                    if(studentStatusVO.getFatherIdcard().equalsIgnoreCase(studentStatusVO.getMotherIdcard())){
                        fullBack +="提交的父亲和母亲证件号码相同！";
                        flag = true;
                    }
                }

                // 通过学校名称获取学校id
                if (ObjectUtils.isEmpty(studentStatusVO.getSchoolName())) {
                    fullBack += "学校名称不能为空！";
                    flag = true;
                } else {
                    String schoolName = studentStatusVO.getSchoolName().replaceAll("（", "(").replaceAll("）", ")").trim();
                    studentStatusVO.setSchoolName(schoolName);
                    if (!ObjectUtils.isEmpty(schoolNameMap.get(schoolName))) {
                        studentStatusVO.setSchoolId(schoolNameMap.get(schoolName));
                    } else {
                        studentStatusVO.setSchoolId(shortNameMap.get(schoolName));
                    }
                }

                if (flag) {
                    studentStatusVO.setFullBack(fullBack);
                    errorList.add(JSON.parseObject(JSON.toJSONString(studentStatusVO), Map.class));
                } else {
                    successList.add(JSON.parseObject(JSON.toJSONString(studentStatusVO), Map.class));
                }

            }

            excelReadVO.setCount(successList.size() + errorList.size());
            excelReadVO.setSuccessCount(successList.size());
            excelReadVO.setSuccessList(successList);
            excelReadVO.setErrorList(errorList);
            excelReadVO.setErrorCount(errorList.size());

        } catch (
                AppException appEx) {
            throw appEx;
        } catch (
                IOException e) {
            throw new AppException("读取文件异常:" + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return excelReadVO;


    }

    public ExcelModelVO getModel(ExcelVO vo) {
        return this.getModel(vo.getModelCode(), vo.getExcelVersion(), vo.getDictMap());
    }

    public ExcelModelVO getModel(
            String modelCode, String version, Map<String, List<SelectVO>> dictMap) {
        if (StringUtils.isBlank(modelCode)) {
            throw new AppException("模板编号不能为空");
        }
        QueryWrapper<ExcelModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ExcelModel::getModelCode, modelCode);
        if (StringUtils.isBlank(version)) {
            queryWrapper.lambda().eq(ExcelModel::getNewFlag, BoolEnum.TRUE.getType());
        } else {
            queryWrapper.lambda().eq(ExcelModel::getExcelVersion, version);
        }
        ExcelModel excelModel = excelModelService.getOne(queryWrapper, false);
        if (excelModel == null) {
            throw new AppException("未找到excel模板信息");
        }
        ExcelModelVO excelModelVO = Convert.convert(ExcelModelVO.class, excelModel);
        // 获取字段信息
        List<ExcelParamVO> paramVOList = this.getByModelId(excelModelVO.getId());
        for (ExcelParamVO excelParamVO : paramVOList) {
            if (excelParamVO.getHeaderBgColor() == null) {
                excelParamVO.setHeaderBgColor(excelModelVO.getHeaderBgColor());
            }
            if (excelParamVO.getHeaderColor() == null) {
                excelParamVO.setHeaderColor(excelModelVO.getHeaderColor());
            }
            if (excelParamVO.getBodyBgColor() == null) {
                excelParamVO.setBodyBgColor(excelModelVO.getBodyBgColor());
            }
            if (excelParamVO.getBodyColor() == null) {
                excelParamVO.setBodyColor(excelModelVO.getBodyColor());
            }
            if (StringUtils.isBlank(excelParamVO.getWrapText())) {
                excelParamVO.setWrapText(excelModelVO.getWrapText());
            }
            if (StringUtils.isBlank(excelParamVO.getFontName())) {
                excelParamVO.setFontName(excelModelVO.getFontName());
            }
            if (excelParamVO.getFontSize() == null) {
                excelParamVO.setFontSize(excelModelVO.getFontSize());
            }
            if (excelParamVO.getBorderSize() == null) {
                excelParamVO.setBorderSize(excelModelVO.getBorderSize());
            }
            if (excelParamVO.getBorderColor() == null) {
                excelParamVO.setBorderColor(excelModelVO.getBorderColor());
            }
            if (ExcelFieldVO.CellTypeEnum.SELECT.getType().equals(excelParamVO.getCellType())
                    || ExcelFieldVO.CellTypeEnum.MULTIPLESELECT
                    .getType()
                    .equals(excelParamVO.getCellType())) {
                String dictField = excelParamVO.getDictField();
                if (StringUtils.isBlank(dictField)) {
                    dictField = excelParamVO.getKey();
                }
                if (dictMap != null && dictMap.containsKey(dictField)) {
                    excelParamVO.setCodeList(dictMap.get(dictField));
                } else {
                    List<SelectVO> selectList = sysDictService.getDictByDictField(dictField);
                    excelParamVO.setCodeList(selectList);
                }
            }
        }
        excelModelVO.setParamVOList(paramVOList);
        if (StringUtils.isBlank(excelModelVO.getExcelType())) {
            excelModelVO.setExcelType(ExcelTypeEnum.xls.toString());
        }
        if (StringUtils.isBlank(excelModelVO.getExcelMode())) {
            excelModelVO.setExcelMode("2");
        }
        return excelModelVO;
    }

    public List<ExcelParamVO> getByModelId(String excelModelId) {
        QueryWrapper<ExcelParam> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ExcelParam::getExcelModelId, excelModelId)
                .orderByAsc(ExcelParam::getOrderNo)
                .orderByAsc(ExcelParam::getCreateTime);
        List<ExcelParam> list = excelParamService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<ExcelParamVO> voList = Convert.toList(ExcelParamVO.class, list);
        return voList;
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0009", title = "学籍信息新增-excel导入保存", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "EduStudentStatus0009",
            operationName = "学籍信息新增-excel导入保存",
            dataType = "batch",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void addExcel(EduStudentStatusExcelSaveVO vo) {
        Integer year = eduHelper.thisYear();
        String areaCode = SessionUtil.getAreaCode();
        List<EduStudentStatusVO> eduStudentStatusVOList = vo.getEduStudentStatusVOList();
        if (CollectionUtils.isEmpty(eduStudentStatusVOList)) {
            throw new AppException("没有传入需要保存的信息");
        }
        for (EduStudentStatusVO studentStatusVO : eduStudentStatusVOList) {
            studentStatusVO.setAreaCode(areaCode);
            studentStatusVO.setYear(year);
            //保存前校验
            checkSave(studentStatusVO);
            //保存数据
            EduStudentStatus entity = Convert.convert(EduStudentStatus.class, studentStatusVO);
            if (!ObjectUtils.isEmpty(studentStatusVO.getIdcard())) {
                QueryWrapper<EduStudentStatus> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(EduStudentStatus::getIdcard, studentStatusVO.getIdcard());
                List<EduStudentStatus> list = eduStudentStatusService.list(queryWrapper);
                if (!CollectionUtils.isEmpty(list)) {
                    for (EduStudentStatus eduStudentStatus : list) {
                        entity.setStudentStatusId(eduStudentStatus.getStudentStatusId());
                    }
                    eduStudentStatusService.updateById(entity);
                } else {
                    eduStudentStatusService.save(entity);
                }
            }
        }
    }

    @Override
    @OpApi(funcCode = "EduStudentStatus0010", title = "学籍信息错误数据下载", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void downloadErrorExcel(StudentStatusFileVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO=getModel(excelVO);
        String fileName = vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        List<Object> errorList = Convert.toList(Object.class, vo.getErrorList());
        excelCommonHelper.downloadExcelBean(excelModelVO,errorList,fileName,response);
    }

    private List<SelectVO> getSchoolDictMap() {
        HashMap<String, Object> map = new HashMap<>();
            map.put("schoolNature", "0");
            map.put("recruitStatus", "0");
            map.put("preFlag", "1");

        List<EduSchoolVO> schoolList = eduSchoolService.selectSchoolList(map);
        List<SelectVO> schoolDictList = new ArrayList<>();
        schoolList.forEach(
                item -> {
                    SelectVO selectVO = new SelectVO();
                    selectVO.setDictKey(item.getOrgId());
                    selectVO.setDictValue(item.getShortName());
                    selectVO.setDictField("schoolName");
                    selectVO.setFieldName("学校");
                    schoolDictList.add(selectVO);
                });
        return schoolDictList;
    }

}
